package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.management.Query;
import java.util.List;
import java.util.Map;

@DubboService   //服务提供者暴露接口
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 分页查询用户
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public IPage findAllUsers(Integer page, Integer pagesize) {
        return userInfoMapper.selectPage(new Page<UserInfo>(page,pagesize),null);
    }

    @Override
    public UserInfo findById(Long id) {
        return userInfoMapper.selectById(id);
    }

    /**
     * 通过id数组查询用户数据Map
     *
     * @param ids
     * @param userInfo
     * @return
     */
    @Override
    public Map<Long, UserInfo> findByIds(List<Long> ids, UserInfo userInfo) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getId, ids);
        if (userInfo != null) {
            //如果传入性别条件不为空，则添加判断
            if (StringUtils.isNotEmpty(userInfo.getGender())) {
                wrapper.eq(UserInfo::getGender, userInfo.getGender());
            }
            //如果传入年龄条件不为空，则添加判断
            if (userInfo.getAge() != null) {
                wrapper.lt(UserInfo::getAge, userInfo.getAge());
            }
            //昵称模糊查询
            if(userInfo.getNickname() != null){
                wrapper.like(UserInfo::getNickname,userInfo.getNickname());
            }
        }
        List<UserInfo> list = userInfoMapper.selectList(wrapper);

        Map<Long, UserInfo> map = CollUtil.fieldValueMap(list, "id");
        return map;
    }
}
